package com.hig.onlineexam.controller;

import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hig.exam.domain.ExamTaskManager;
import com.hig.exam.domain.ExamTaskQuestions;
import com.hig.exam.domain.RangesDto;
import com.hig.exam.mapper.ExamTaskQuestionsMapper;
import com.hig.exam.service.IExamTaskManagerService;
import com.hig.exam.service.impl.ExamTaskManagerServiceImpl;
import com.hig.onlineexam.domain.ExamFinishAnswer;
import com.hig.onlineexam.mapper.ExamFinishAnswerMapper;
import com.hig.questions.domain.ExamQuestionsProperty;
import com.hig.questions.mapper.ExamQuestionsPropertyMapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.hig.onlineexam.domain.ExamUserScore;
import com.hig.onlineexam.service.IExamUserScoreService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 考试成绩Controller
 *
 * @author qnsdt
 * @date 2023-03-03
 */
@RestController
@RequestMapping("/onlineexam/userscore")
@Api("考试成绩")
public class ExamUserScoreController extends BaseController {
    @Autowired
    private IExamUserScoreService examUserScoreService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IExamTaskManagerService examTaskManagerService;

    /**
     * 查询考试成绩列表
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:userscore:list')")
    @GetMapping("/list")
    @ApiOperation("查询用户成绩，可以 传入examCode 和userCode  ")
    public TableDataInfo list(ExamUserScore examUserScore) {
        Gson gson = new Gson();
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (!loginUser.getUser().isAdmin()) {
            String userCode = loginUser.getUser().getUserCode();
            examUserScore.setUserCode(userCode);
        }
        List<ExamUserScore> list = examUserScoreService.selectExamUserScoreList(examUserScore);
        for (ExamUserScore userScore : list) {
            String examCode = userScore.getExamCode();
            ExamTaskManager examTaskManager = examTaskManagerService.selectExamTaskManagerById(examCode);
            if (ObjectUtil.isNotNull(examTaskManager)) {
                Long status = examTaskManager.getStatus();
                userScore.setStatus(ObjectUtil.isNotNull(status) ? status.intValue() : 0);
            }


            String rangesJson = userScore.getRangesJson();
            if (StringUtils.isNotEmpty(rangesJson)) {
                List<RangesDto> rangesList = gson.fromJson(rangesJson, new TypeToken<List<RangesDto>>() {
                }.getType());
                userScore.setRanges(rangesList);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出考试成绩列表
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:userscore:export')")
    @Log(title = "考试成绩", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ExamUserScore examUserScore, HttpServletResponse response) {
        List<ExamUserScore> list = examUserScoreService.selectExamUserScoreList(examUserScore);
        ExcelUtil<ExamUserScore> util = new ExcelUtil<ExamUserScore>(ExamUserScore.class);
        util.exportExcel(response, list, "考试成绩数据");
    }

    @Autowired
    private ExamTaskQuestionsMapper examTaskQuestionsMapper;
    @Autowired
    private ExamQuestionsPropertyMapper propertyMapper;
    @Autowired
    private ExamFinishAnswerMapper finishAnswerMapper;

    @ApiOperation("错题记录")
    @GetMapping("wrong")
    public AjaxResult wrong(@RequestParam String examCode) {
        ExamTaskQuestions et = new ExamTaskQuestions();
        et.setExamCode(examCode);
        List<ExamTaskQuestions> examTaskQuestions = examTaskQuestionsMapper.selectExamTaskQuestionsList(et);
        if (CollectionUtil.isEmpty(examTaskQuestions)) {
            throw new RuntimeException("查询不到题目信息");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userCode = loginUser.getUser().getUserCode();
        for (ExamTaskQuestions examTaskQuestion : examTaskQuestions) {
            String questionsCode = examTaskQuestion.getQuestionsCode();
            ExamQuestionsProperty examQuestionsProperty = propertyMapper.selectExamQuestionsPropertyById(questionsCode);
            examTaskQuestion.setProperty(examQuestionsProperty);

            ExamFinishAnswer examFinishAnswer = finishAnswerMapper.selectByUniqueKeys(examCode, userCode, questionsCode);
            examTaskQuestion.setFinishAnswer(examFinishAnswer);

        }
        return AjaxResult.success(examTaskQuestions);
    }

    /**
     * 获取考试成绩详细信息
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:userscore:query')")
    @GetMapping(value = "/{examCode}")
    public AjaxResult getInfo(@PathVariable("examCode") String examCode) {
        return AjaxResult.success(examUserScoreService.selectExamUserScoreById(examCode));
    }

    /**
     * 新增考试成绩
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:userscore:add')")
    @Log(title = "考试成绩", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExamUserScore examUserScore) {
        return toAjax(examUserScoreService.insertExamUserScore(examUserScore));
    }

    /**
     * 维护考试成绩
     */
    @PostMapping("/into")
    public AjaxResult into(@RequestBody ExamUserScore examUserScore) {
        return toAjax(examUserScoreService.intoExamUserScore(examUserScore));
    }

    /**
     * 修改考试成绩
     */
    @PreAuthorize("@ss.hasPermi('onlineexam:userscore:edit')")
    @Log(title = "考试成绩", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExamUserScore examUserScore) {
        return toAjax(examUserScoreService.updateExamUserScore(examUserScore));
    }

    /**
     * 删除考试成绩
     */
    @PreAuthorize("@ss.hasPermi('score:score:remove')")
    @Log(title = "考试成绩", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(examUserScoreService.deleteExamUserScoreByIds(ids));
    }
}
